#!/bin/bash

setup_environment() {
    export PATH=/usr/local/git/bin:$PATH 
    export JAVA_HOME=/usr/lib/jvm/java-1.8.0
    export PATH=$JAVA_HOME/bin:$PATH
    export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tool.jar
    export MAVEN_HOME=/home/work/apache-maven-3.5.4
    export PATH=${PATH}:${MAVEN_HOME}/bin
    export NODEJS_HOME=/home/work/nodejs
    export PATH=$NODEJS_HOME/bin:$PATH
}

clone_repository() {
    local repo_dir="/home/work/git_workspace"
    cd $repo_dir || exit 1
    rm -rf $repo_dir/*
    git clone git@gitee.com:yanjiuzongyuan/zypark-cloud.git
    cd zypark-cloud || exit 1
    git checkout release-lts
    echo "-------------Git代码克隆完成-------------"
}

build_frontend() {
    echo "-------------开始编译打包前端-------------"
    cd /home/work/git_workspace/zypark-cloud/zypark-ui-vue3 || exit 1

    npm install --registry=https://registry.npmmirror.com --legacy-peer-deps
    npm run build:prod

    rm -rf /home/work/zypark_app/dist-prod
    cp -r dist-prod/ /home/work/zypark_app/
    echo "-------------前端编译并传输完成-------------"
    sleep 3
}

build_backend() {
    echo "-------------开始编译后端-------------"
    cd /home/work/git_workspace/zypark-cloud || exit 1
    mvn clean install -Dmaven.test.skip=true
    echo "-------------后端编译完成-------------"
    sleep 3
}

transfer_backend_services() {
    echo "-------------本地后端服务传输|gateway|infra|system|report|xxl-job|bpm|pay|-------------"
    local app_dir="/home/work/zypark_app"
    
    cp -r /home/work/git_workspace/zypark-cloud/zypark-gateway/target/zypark-gateway.jar $app_dir/
    cp -r /home/work/git_workspace/zypark-cloud/zypark-module-infra/zypark-module-infra-biz/target/zypark-module-infra-biz.jar $app_dir/
    cp -r /home/work/git_workspace/zypark-cloud/zypark-module-system/zypark-module-system-biz/target/zypark-module-system-biz.jar $app_dir/
    cp -r /home/work/git_workspace/zypark-cloud/zypark-module-report/zypark-module-report-biz/target/zypark-module-report-biz.jar $app_dir/
    cp -r /home/work/git_workspace/zypark-cloud/zypark-xxl-job/xxl-job-admin/target/xxl-job-admin-2.4.0-SNAPSHOT.jar $app_dir/

    cp -r /home/work/git_workspace/zypark-cloud/zypark-module-bpm/zypark-module-bpm-biz/target/zypark-module-bpm-biz.jar $app_dir/
    cp -r /home/work/git_workspace/zypark-cloud/zypark-module-pay/zypark-module-pay-biz/target/zypark-module-pay-biz.jar $app_dir/
    
    echo "-------------本地后端服务传输完成|gateway|infra|system|report|xxl-job|bpm|pay|-------------"
}


start_backend_service() {
    /app/start/backend_start.sh
    echo "-------------本地后端服务启动完成-------------"
}


main() {
    setup_environment
    clone_repository
    build_frontend
    build_backend
    transfer_backend_services
    start_backend_service
}


main
